package com.wb.mas.ui.auth;

import android.app.Application;
import android.text.TextUtils;

import com.blankj.utilcode.util.SPUtils;
import com.wb.mas.R;
import com.wb.mas.app.Constants;
import com.wb.mas.app.DictInfoTypeKey;
import com.wb.mas.app.SPKeys;
import com.wb.mas.app.UUidUtils;
import com.wb.mas.data.DemoRepository;
import com.wb.mas.entity.DicInfoEntity;
import com.wb.mas.entity.DicInfoResponse;
import com.wb.mas.entity.LocationWrapper;
import com.wb.mas.entity.RootApiBean;
import com.wb.mas.entity.SubmitedAuthResponse;
import com.wb.mas.storage.LocationDao;
import com.wb.mas.ui.view.datepicker.DateFormatUtils;
import com.wb.mas.utils.response.ResultException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AuthPIVIewModel extends AuthBaseViewModel {


    private String currentDictType;
    private List<DicInfoEntity> dicInfoList;

    private LocationDao locationDao = new LocationDao();

    public void onItemSelected(String title, int position) {


        if (currentDictType == null || dicInfoList == null || position >= dicInfoList.size())
            return;
        if (currentDictType.equals(DictInfoTypeKey.common_education)) {
            edu.set(dicInfoList.get(position));

        } else if (currentDictType.equals(DictInfoTypeKey.number_of_children)) {
            childrenNum.set(dicInfoList.get(position));

        } else if (currentDictType.equals(DictInfoTypeKey.number_of_family_members)) {

            familyNum.set(dicInfoList.get(position));
        } else if (currentDictType.equals(DictInfoTypeKey.common_homeowner)) {

            housingType.set(dicInfoList.get(position));
            if ("common_homeowner3".equalsIgnoreCase(housingType.get().dictCode)) {//租房类型

                isZufangShow.set(true);
            } else {
                isZufangShow.set(false);
            }

        } else if (currentDictType.equals(DictInfoTypeKey.rental_scope)) {
            housingRentType.set(dicInfoList.get(position));

        }
    }

    public void setTime(long timestamp) {
        if (tempTime != null) {

            if (tempTime == birthday) {
                tempTime.set(DateFormatUtils.long2Str(timestamp, false));
            } else if (tempTime == housingStartTime) {

                tempTime.set(DateFormatUtils.long2StrYm(timestamp));
            }
        }
    }

    public class UiChangeEvent {
        public SingleLiveEvent birthdayEvent = new SingleLiveEvent();
        public SingleLiveEvent houseStartTimeEvent = new SingleLiveEvent();
        public SingleLiveEvent<String> showPopupEvent = new SingleLiveEvent();
        public SingleLiveEvent<LocationWrapper> showLocationEvent = new SingleLiveEvent();

    }

    public UiChangeEvent uc = new UiChangeEvent();


    public AuthPIVIewModel(@NonNull Application application, DemoRepository model) {
        super(application, model);
        setTitleText(getString(R.string.auth_pi_page_title_name));
    }

    public ObservableField<String> tempTime = null;
    public ObservableField<String> birthday = new ObservableField<>("");
    public ObservableField<String> housingStartTime = new ObservableField<>("");
    public ObservableField<DicInfoEntity> edu = new ObservableField<DicInfoEntity>();
    public ObservableField<String> email = new ObservableField<>("");
    public ObservableField<String> province = new ObservableField<>("");
    public ObservableField<String> city = new ObservableField<>("");
    public ObservableField<String> town = new ObservableField<>("");
    public ObservableField<String> region = new ObservableField<>("");
    public ObservableField<String> detailAddress = new ObservableField<>("");
    public ObservableField<String> bigRegion = new ObservableField<>("");
    public ObservableField<String> smallRegion = new ObservableField<>("");
    public ObservableField<String> postCode = new ObservableField<>("");
    public ObservableField<DicInfoEntity> housingType = new ObservableField<>();
    public ObservableField<DicInfoEntity> housingRentType = new ObservableField<>();
    public ObservableField<String> matherName = new ObservableField<>("");
    public ObservableField<DicInfoEntity> familyNum = new ObservableField<>();
    public ObservableField<DicInfoEntity> childrenNum = new ObservableField<>();
    public ObservableField<Boolean> isZufangShow = new ObservableField<>(false);


    public BindingCommand birthdayClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempTime = birthday;
            uc.birthdayEvent.setValue("");
        }
    });

    public BindingCommand housingStartTimeClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            tempTime = housingStartTime;

            uc.houseStartTimeEvent.setValue("");
        }
    });
    public BindingCommand eduClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            getDictsBykey(DictInfoTypeKey.common_education);
        }
    });
    public BindingCommand provinceClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            ArrayList<String> provinceList = locationDao.getProvince();
            uc.showLocationEvent.setValue(new LocationWrapper(provinceList, province, getString(R.string.auth_page_please_select_province)));


        }
    });
    public BindingCommand cityClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {


            if (StringUtils.isEmpty(province.get())) {
                ToastUtils.showShort(getString(R.string.auth_page_please_select_province));
                return;
            }
            ArrayList<String> cityList = locationDao.getCity(province.get());
            uc.showLocationEvent.setValue(new LocationWrapper(cityList, city, getString(R.string.auth_page_please_select_city)));
        }
    });
    public BindingCommand townClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            if (StringUtils.isEmpty(city.get())) {
                ToastUtils.showShort(getString(R.string.auth_page_please_select_city));
                return;
            }
            ArrayList<String> townList = locationDao.getTown(province.get(), city.get());
            uc.showLocationEvent.setValue(new LocationWrapper(townList, town, getString(R.string.auth_page_please_select_town)));

        }
    });
    public BindingCommand regionClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            if (StringUtils.isEmpty(town.get())) {
                ToastUtils.showShort(getString(R.string.auth_page_please_select_town));
                return;
            }
            ArrayList<String> areaList = locationDao.getArea(province.get(), city.get(), town.get());
            uc.showLocationEvent.setValue(new LocationWrapper(areaList, region, getString(R.string.auth_page_please_select_area)));


        }
    });
    public BindingCommand housingTypeClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            getDictsBykey(DictInfoTypeKey.common_homeowner);

        }
    });
    public BindingCommand familyNumClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            getDictsBykey(DictInfoTypeKey.number_of_family_members);

        }
    });
    public BindingCommand chridrenNumClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            getDictsBykey(DictInfoTypeKey.number_of_children);

        }
    });
    public BindingCommand housingTimeClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            getDictsBykey(DictInfoTypeKey.rental_scope);

        }
    });
    public BindingCommand onClickNextStep = new BindingCommand(new BindingAction() {
        @Override
        public void call() {


            if (TextUtils.isEmpty(birthday.get())

            ) {

                ToastUtils.showShort(R.string.auth_pi_please_input_birthday);
                return;
            }
            if (TextUtils.isEmpty(edu.get().dictValue)) {

                ToastUtils.showShort(R.string.auth_pi_please_input_edu);
                return;
            }
            if (TextUtils.isEmpty(email.get())) {

                ToastUtils.showShort(R.string.auth_pi_please_input_email);
                return;
            }
            if (TextUtils.isEmpty(province.get())) {

                ToastUtils.showShort(R.string.auth_pi_please_input_province);
                return;
            }
            if (TextUtils.isEmpty(city.get())) {

                ToastUtils.showShort(R.string.auth_pi_please_input_city);
                return;
            }
            if (TextUtils.isEmpty(town.get())) {

                ToastUtils.showShort(R.string.auth_pi_please_input_town);
                return;
            }
            if (TextUtils.isEmpty(region.get())) {

                ToastUtils.showShort(R.string.auth_pi_please_input_region);
                return;
            }
            if (TextUtils.isEmpty(detailAddress.get())) {

                ToastUtils.showShort(R.string.auth_pi_please_input_detail_address);
                return;
            }


            if (TextUtils.isEmpty(bigRegion.get())) {

                ToastUtils.showShort(R.string.auth_pi_please_input_big_region);
                return;
            }
            if (TextUtils.isEmpty(smallRegion.get())) {

                ToastUtils.showShort(R.string.auth_pi_please_input_samll_region);
                return;
            }
            if (TextUtils.isEmpty(postCode.get())) {

                ToastUtils.showShort(R.string.auth_pi_please_input_post_code);
                return;
            }
            if (TextUtils.isEmpty(housingType.get().dictValue)) {

                ToastUtils.showShort(R.string.auth_pi_please_input_house_type);
                return;
            }
            if (TextUtils.isEmpty(housingStartTime.get())) {

                ToastUtils.showShort(R.string.auth_pi_please_input_house_start_time);
                return;
            }
            if (TextUtils.isEmpty(matherName.get())) {

                ToastUtils.showShort(R.string.auth_pi_please_input_mother_name);
                return;
            }
            if (TextUtils.isEmpty(familyNum.get().dictValue)) {

                ToastUtils.showShort(R.string.auth_pi_please_input_family_num);
                return;
            }
            if (TextUtils.isEmpty(childrenNum.get().dictValue)) {

                ToastUtils.showShort(R.string.auth_pi_please_input_children_num);
                return;
            }


            doUploadPersonalInfo();

        }

    });


//    "address": "bbb",       //详细地址
//            “isInformationWrong”:1   //如果是资料退回再次上传的 传1  要不是不传
//            "motherName": "h",    //母亲姓名
//            "region": "MARGA MUKTI",  //区域
//            "city": "MUKO MUKO",   //市
//            "userUuid": "20190423953",
//            "email": "hhh",        // 邮箱
//            "smallRegionCode": "9",   //小区号
//            "residenceStartTime": "2019-01",       //居住时间
//            "sonsNum": "number_of_children4",     // 子女数量数据字典code
//            "province": "BENGKULU",    //省
//            "birthday": "1994-01-01",    //生日
//            "commonParam": 公参,
//            "authPageCode": "personage_info_code",   //认证步骤code
//            "zipCode": "89",     //邮编
//            "town": "PENARIK",  //镇
//            "bigRegionCode": "99",   //大区号
//            "education": "common_education_4",   // 教育字典code
//            "rentalScopeCode": "rental_scope_1",    //租金类型code 只有当租房类型是这个时候才有这个字段
//            "homeowner": "common_homeowner3",   //居住类型字典code
//            "channel": "1",
//            "familyNum": "number_of_family_members3"    //家庭成员字典code

    private void doUploadPersonalInfo() {

        showDialog();
        Map<String, Object> params = new HashMap<>();
        if (SPUtils.getInstance().getBoolean(SPKeys.SP_ISBACK)) {
            params.put("isInformationWrong", "1");

        }
        params.put("address", detailAddress.get());
        params.put("motherName", matherName.get());
        params.put("region", TextUtils.isEmpty(region.get()) ? "" : region.get());
        params.put("city", city.get());
        params.put("userUuid", UUidUtils.getUUid());
        params.put("email", email.get());
        params.put("smallRegionCode", smallRegion.get());
        params.put("residenceStartTime", housingStartTime.get());
        params.put("sonsNum", childrenNum.get().dictCode);
        params.put("province", province.get());
        params.put("birthday", birthday.get());
        params.put("authPageCode", Constants.AUTH_PAGE_CODE_PERSONAGE_INFO_CODE);
        params.put("zipCode", postCode.get());
        params.put("town", TextUtils.isEmpty(town.get()) ? "" : town.get());
        params.put("bigRegionCode", bigRegion.get());
        params.put("education", edu.get().dictCode);
        if (housingRentType != null && housingRentType.get() != null && !TextUtils.isEmpty(housingRentType.get().dictCode)) {
            params.put("rentalScopeCode", housingRentType.get().dictCode);
        }
        params.put("homeowner", housingType.get().dictCode);
        params.put("familyNum", familyNum.get().dictCode);
        model.saveOrUpdateCustomerInfo(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<RootApiBean>() {
                    @Override
                    public void accept(RootApiBean rootApiBean) throws Exception {

                        dismissDialog();

                        if (rootApiBean != null && rootApiBean.getStatus() == 200) {
                            AuthJumpManager.jumpToNextPage(Constants.AUTH_PAGE_CODE_PERSONAGE_INFO_CODE);
                            finish();

                        } else {
                            if (rootApiBean != null && !TextUtils.isEmpty(rootApiBean.getMessage())) {
                                ToastUtils.showShort(rootApiBean.getMessage());
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        KLog.e("error:" + throwable.getMessage());
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                });
    }


    public void getDictsBykey(final String dictType) {
        showDialog();
        Map<String, Object> dictParams = new HashMap<>();
        dictParams.put("dictType", dictType);
        model.getDicInfo(dictParams)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DicInfoResponse>() {
                    @Override
                    public void accept(DicInfoResponse dicInfoResponse) throws Exception {
                        dismissDialog();
                        if (dicInfoResponse == null) return;


                        showPopWindow(dictType, dicInfoResponse.getData());


                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        KLog.e("error:" + throwable.getMessage());
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                });

    }

    private void showPopWindow(String dictType, List<DicInfoEntity> data) {
        this.currentDictType = dictType;
        this.dicInfoList = data;
        uc.showPopupEvent.setValue("");
    }


    public String getCurrentDictType() {
        return this.currentDictType;
    }

    public List<DicInfoEntity> getCurrentDictList() {
        return this.dicInfoList;
    }


    private void showLocationPop(List<String> contentList, ObservableField<String> bindedField) {

    }


    @Override
    public void onCreate() {
        super.onCreate();
        getSubmitedInfo(Constants.AUTH_PAGE_CODE_PERSONAGE_INFO_CODE);
    }


    @Override
    protected void onSubmittedResponse(SubmitedAuthResponse response) {
        super.onSubmittedResponse(response);

        if (response != null && response.getData() != null && response.getData().getPersonageInfo() != null) {
            SubmitedAuthResponse.DataBean.PersonageInfoBean personageInfo = response.getData().getPersonageInfo();


            birthday.set(personageInfo.getBirthday());
            edu.set(new DicInfoEntity(personageInfo.getEducationValue(), personageInfo.getEducation()));
            email.set(personageInfo.getEmail());
            province.set(personageInfo.getProvince());
            city.set(personageInfo.getCity());
            town.set(personageInfo.getTown());
            region.set(personageInfo.getRegion());
            detailAddress.set(personageInfo.getAddress());
            bigRegion.set(personageInfo.getBigRegionCode());
            smallRegion.set(personageInfo.getSmallRegionCode());
            postCode.set(personageInfo.getZipCode());
            housingType.set(new DicInfoEntity(personageInfo.getHomeownerValue(), personageInfo.getHomeowner()));
            housingRentType.set(new DicInfoEntity(personageInfo.getRentalScopeValue(), personageInfo.getRentalScopeCode()));
            matherName.set(personageInfo.getMotherName());
            familyNum.set(new DicInfoEntity(personageInfo.getFamilyNumValue(), personageInfo.getFamilyNum()));
            childrenNum.set(new DicInfoEntity(personageInfo.getSonsNumValue(), personageInfo.getSonsNum()));
            housingStartTime.set(personageInfo.getResidenceStartTime());

            if ("common_homeowner3".equalsIgnoreCase(housingType.get().dictCode)) {//租房类型
                isZufangShow.set(true);
            } else {
                isZufangShow.set(false);
            }
        }
    }


}
